//
//  KICropImageView.m
//  Kitalker
//
//  Created by 杨 烽 on 12-8-9.
//
//

#import "KICropImageView.h"

@implementation KICropImageView
@synthesize delegate;

- (void)show
{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
}
- (void)hide
{
    [self removeFromSuperview];
}

- (id)initWithCropSize:(CGSize)size
{
    
    if(self = [super initWithFrame:[UIScreen mainScreen].bounds])
    {
        [self setCropSize:size];
    }

    
    return self;
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    [[self scrollView] setFrame:self.bounds];
    [self.maskView0 setFrame:self.bounds];
    
    if (CGSizeEqualToSize(_cropSize, CGSizeZero)) {
        [self setCropSize:CGSizeMake(100, 100)];
    }
    
    self.backgroundColor = [UIColor blackColor];
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[closeBtn setTitle:NSLocalizedString(@"关闭",@"") forState:UIControlStateNormal];
    closeBtn.frame = CGRectMake(10, self.bounds.size.height-35, 60, 30);
	[closeBtn addTarget:self action:@selector(onCloseBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:closeBtn];
    
    UIButton *useImageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[useImageBtn setTitle:NSLocalizedString(@"使用照片",@"") forState:UIControlStateNormal];
    useImageBtn.frame = CGRectMake(230, self.bounds.size.height-35, 80, 30);
	[useImageBtn addTarget:self action:@selector(onUseImageBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:useImageBtn];
    
}

- (void) onCloseBtnClicked:(id) sender
{
    if([delegate respondsToSelector:@selector(kiCropImageView:cancelEditingImage:)])
    {
        [delegate kiCropImageView:self cancelEditingImage:nil];
    }
}

- (void) onUseImageBtnClicked:(id) sender
{
    if([delegate respondsToSelector:@selector(kiCropImageView:didFinishEditingImage:)])
    {
        [delegate kiCropImageView:self didFinishEditingImage:[self cropImage]];
    }
}


- (UIScrollView *)scrollView {
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] init];
        [_scrollView setDelegate:self];
        [_scrollView setBounces:NO];
        [_scrollView setShowsHorizontalScrollIndicator:NO];
        [_scrollView setShowsVerticalScrollIndicator:NO];
        [self addSubview:_scrollView];
    }
    return _scrollView;
}

- (UIImageView *)imageView {
    if (_imageView == nil) {
        _imageView = [[UIImageView alloc] init];
        [[self scrollView] addSubview:_imageView];
    }
    return _imageView;
}

- (KICropImageMaskView *)maskView0 {
    if (_maskView0 == nil) {
        _maskView0 = [[KICropImageMaskView alloc] init];
        [_maskView0 setBackgroundColor:[UIColor clearColor]];
        [_maskView0 setUserInteractionEnabled:NO];
        [self addSubview:_maskView0];
        [self bringSubviewToFront:_maskView0];
    }
    return _maskView0;
}

- (void)setImage:(UIImage *)image {
    if (image != _image) {
        _image = image;
    }
    [[self imageView] setImage:_image];
    
    [self updateZoomScale];
}

- (void)updateZoomScale {
    CGFloat width = _image.size.width;
    CGFloat height = _image.size.height;
    
    if (width<320&& width>10) {
        CGFloat bilv=320.0/width;
        height=height*bilv;
        width=320;
    }
    
    [[self imageView] setFrame:CGRectMake(0, 0, width, height)];
    
    CGFloat xScale = _cropSize.width / width;
    CGFloat yScale = _cropSize.height / height;
    
    CGFloat min = MAX(xScale, yScale);
    CGFloat max = 1.0;
    
    if (min > max)
    {
        min = max;
    }
    
    [[self scrollView] setMinimumZoomScale:min];
    [[self scrollView] setMaximumZoomScale:max + 5.0f];
    
    [[self scrollView] setZoomScale:min animated:NO];
    [[self scrollView] setContentOffset:CGPointMake(0, 0)];
}

- (void)setCropSize:(CGSize)size {
    _cropSize = size;
    [self updateZoomScale];
    
    CGFloat width = _cropSize.width;
    CGFloat height = _cropSize.height;
    
    CGFloat x = (CGRectGetWidth(self.bounds) - width) / 2;
    CGFloat y = (CGRectGetHeight(self.bounds) - height) / 2;

//    [[self maskView] setCropSize:_cropSize];
    
    CGFloat top = y;
    CGFloat left = x;
    CGFloat right = CGRectGetWidth(self.bounds)- width - x;
    CGFloat bottom = CGRectGetHeight(self.bounds)- height - y;
    _imageInset = UIEdgeInsetsMake(top, left, bottom, right);
    [[self scrollView] setContentInset:_imageInset];
    
    [[self scrollView] setContentOffset:CGPointMake(0, 0)];
}

- (UIImage *)cropImage {
    CGFloat zoomScale = [self scrollView].zoomScale;
    
    CGFloat offsetX = [self scrollView].contentOffset.x;
    CGFloat offsetY = [self scrollView].contentOffset.y;
    CGFloat aX = offsetX>=0 ? offsetX+_imageInset.left : (_imageInset.left - ABS(offsetX));
    CGFloat aY = offsetY>=0 ? offsetY+_imageInset.top : (_imageInset.top - ABS(offsetY));
    
    aX = aX / zoomScale;
    aY = aY / zoomScale;
    
    CGFloat aWidth = MIN(_cropSize.width / zoomScale, _cropSize.width);
    CGFloat aHeight = MIN(_cropSize.height / zoomScale, _cropSize.height);
    
    if (zoomScale < 1)
    {
        aWidth = MAX(_cropSize.width / zoomScale, _cropSize.width);
        aHeight = MAX(_cropSize.height / zoomScale, _cropSize.height);
    }
    
    UIImage *image = [_image cropImageWithX:aX y:aY width:aWidth height:aHeight];
    
    image = [image resizeToWidth:_cropSize.width height:_cropSize.height];

    return image;
}

#pragma UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return [self imageView];
}

@end

#pragma KISnipImageMaskView

#define kMaskViewBorderWidth 2.0f

@implementation KICropImageMaskView

- (void)setCropSize:(CGSize)size {
    CGFloat x = (CGRectGetWidth(self.bounds) - size.width) / 2;
    CGFloat y = (CGRectGetHeight(self.bounds) - size.height) / 2;
    _cropRect = CGRectMake(x, y, size.width, size.height);
    
    [self setNeedsDisplay];
}

- (CGSize)cropSize {
    return _cropRect.size;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(ctx, 0, 0, 0, 0.6);
    CGContextFillRect(ctx, self.bounds);
    
    CGContextSetStrokeColorWithColor(ctx, [UIColor whiteColor].CGColor);
    CGContextStrokeRectWithWidth(ctx, _cropRect, kMaskViewBorderWidth);
    
    CGContextClearRect(ctx, _cropRect);
}
@end
